8  Packages and Libraries in R

8.0.1 Installing Packages

Packages in R can be installed from various sources, but the Comprehensive R Archive Network (CRAN) is the most common source. To install a package from CRAN, you can use the install.packages() function. This function downloads and installs the package binaries.

  • You only need to install a package once (unless you’re updating it to a newer version).

8.0.2 Loading Packages

After a package is installed, it must be loaded into the session to use its functionalities. To load a package, use the library() function.

  • For example, to install the ggplot2 package, which is a very popular package for data visualization, you would use the following command in the R console:
install.packages("ggplot2")`
library(ggplot2)`

8.0.3 Basic Plotting and Visualization

Basic Plots

Using plot().

Advanced Visualizations

With ggplot2().

8.0.4 Example: Creating a Simple Plot with ggplot2

Let’s go through a simple example of installing and loading the ggplot2 package, then using it to create a basic plot.

First, ensure ggplot2 is installed (you only do this once):

Code
install.packages("ggplot2")

Next, load the ggplot2 package:

Now, let’s create a simple scatter plot. We’ll use the mtcars dataset, which is included in base R, plotting mpg (miles per gallon) against hp (horsepower):

Code
ggplot(mtcars, aes(x = hp, y = mpg)) + 
  geom_point() +
  labs(title = "Car Mileage vs. Horsepower", 
       x = "Horsepower", 
       y = "Miles per Gallon")

This command uses ggplot() to initiate the plot, specifying mtcars as the dataset and mapping hp to the x-axis and mpg to the y-axis with aes(). geom_point() adds the points to the plot, and labs() is used to add labels.